﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.ComponentModel;
using System.Collections.ObjectModel;
using System.Linq;
using Nwsfeed;

namespace nwsfeed
{
	/// <summary>
	/// Interaction logic for AddFeedWindow.xaml
	/// </summary>
    public partial class AddFeedWindow : Window, INotifyPropertyChanged
	{
        private MainWindow mainWindow;
        private WebHelper wh;
        private Uri lastDiscoveryTaskId;
		
		private String windowTitle;
        public String WindowTitle { get { return windowTitle; } set { windowTitle = value; OnPropertyChanged("WindowTitle"); } }

        List<RSSFeed> feedsFound = new List<RSSFeed>();
        List<RSSFeed> newFeedsFound = new List<RSSFeed>();

        // UI Properties
        private String label;
        public String Label
        {
            get { return label; }
            set { label = value; OnPropertyChanged("Label"); }
        }
		
		private bool isWorking;
		public bool IsWorking
		{
			get {return isWorking;}
			set {isWorking = value; OnPropertyChanged("IsWorking");}
		}

		public AddFeedWindow()
		{
			this.InitializeComponent();
            this.init();
		}

        public AddFeedWindow(MainWindow mainWindow)
        {
            this.mainWindow = mainWindow;
            this.InitializeComponent();
			Loaded +=new System.Windows.RoutedEventHandler(AddFeedWnd_Loaded);
            init();
        }

        private void init()
        {
            this.DataContext = this;
			this.IsWorking = false;
            wh = new WebHelper();
            wh.DiscoverFeedsCompleted += new DiscoverFeedsCompletedEventHandler(wh_DiscoverFeedsCompleted);

            lastDiscoveryTaskId = null;

            // init UI properties
			WindowTitle = "Add a feed";
            Label = "Type or paste in a web address to search for RSS / Atom feeds.";

            buttonAddFeed.Visibility = Visibility.Hidden;
            buttonAddFeed.IsEnabled = false;
        }

		protected void OnPropertyChanged(string name)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(name));
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

		private void titleMouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
		{
			// TODO: Add event handler implementation here.
			this.DragMove();
		}
		

		private void xButton_Click(object sender, System.Windows.RoutedEventArgs e)
		{
			this.Close();
		}

        private void buttonSearch_Click(object sender, RoutedEventArgs e)
        {
            feedsFound.Clear();
            newFeedsFound.Clear();

            if (Uri.IsWellFormedUriString(textBoxUrl.Text, UriKind.Absolute))
            {
                Uri url = new Uri(textBoxUrl.Text);
                if (url.Scheme.Equals("http") || url.Scheme.Equals("https"))
                {
                    Label = "nwsfeed is searching for feeds, this may take a while...";
				    IsWorking = true;
                    lastDiscoveryTaskId = url;

                    try
                    {
                        wh.DiscoverFeedsAsync(url, lastDiscoveryTaskId);
                    }
                    catch
                    {
						IsWorking = false;
                        return;
                    }
                }
                else
				{
                    Label = "Please specify a valid URL. (e.g. http://www.example.com)";
					IsWorking = false;
				}
            }
            else
			{
                Label = "Please specify a valid URL. (e.g. http://www.example.com)";
				IsWorking = false;
			}
        }


        void wh_DiscoverFeedsCompleted(object sender, DiscoverFeedsCompletedEventArgs e)
        {
            if ((e.UserState as Uri) == lastDiscoveryTaskId)
            {
				IsWorking = false;
                feedsFound = e.Result;
                if (feedsFound != null)
                {
                    foreach (RSSFeed feed in feedsFound)
                    {
                        if (!mainWindow.App.AllreadySubscribedTo(feed))
                            newFeedsFound.Add(feed);
                    }

                    if (feedsFound.Count != 0)
                    {
                        if (newFeedsFound.Count == 1)
                            Label = "1 new feed found";
                        else
                            Label = newFeedsFound.Count.ToString() + " new feeds found";

                        buttonAddFeed.Visibility = Visibility.Visible;
                        buttonAddFeed.IsEnabled = true;
                    }
                    else
                    {
                        Label = "0 feeds found";
                        buttonAddFeed.Visibility = Visibility.Hidden;
                        buttonAddFeed.IsEnabled = false;
                    }
                }
                else 
                {
                    Label = "0 feeds found";
                    buttonAddFeed.Visibility = Visibility.Hidden;
                    buttonAddFeed.IsEnabled = false;
                }
            }
        }
        
        private void buttonAddFeed_Click(object sender, RoutedEventArgs e)
        {
            if (newFeedsFound != null && newFeedsFound.Count != 0)
            {
                // TO DO: for selected item, let user pick
                RSSFeed selectedFeed = newFeedsFound[0];
                mainWindow.App.AddFeed(selectedFeed);
                //mainWindow.App.ActiveProfile.Feeds.Add(selectedFeed);
                Label = "Subscribed to " + selectedFeed.Title;

                // after a new feed was added,
                // start new search session, disable add button
                // TO DO: let the user pick and add other found feeds to which they're not subscribed allready
                feedsFound.Clear();
                newFeedsFound.Clear();

                buttonAddFeed.Visibility = System.Windows.Visibility.Hidden;
                buttonAddFeed.IsEnabled = false;
                
            }
        }

        private void textBoxUrl_TextChanged(object sender, TextChangedEventArgs e)
        {
            lastDiscoveryTaskId = null;
            if (buttonAddFeed != null)
            {
                buttonAddFeed.Visibility = Visibility.Hidden;
                buttonAddFeed.IsEnabled = false;                
            }
            Label = "Type or paste in a web address to search for RSS / Atom feeds.";
            feedsFound.Clear();
            newFeedsFound.Clear();
        }

        private void WindowAddFeed_Closed(object sender, EventArgs e)
        {
            mainWindow.activeDialog = null;
        }

        private void AddFeedWnd_Loaded(object sender, System.Windows.RoutedEventArgs e)
        {
        	var style = (Style)Resources["WindowStyleModal"];
            this.Style = style;
        }
	
		private void AddFeedWnd_Activated(object sender, System.EventArgs e)
		{
			mainWindow.activeDialog = this;
		}
}
}